<template>
  <div class="production-selector">
    <dialog-table ref="selector" :request="getList" :title="title" :request-params="_requestParams"
      :table-column="tableColumns" :dialog-width="'80%'" v-bind="$attrs" @input-row="handleRowClick"
      :columnOption="_columnOption" :oldValue="_previousValue">
      <template #form>
        <!-- 查询条件 -->
        <j-border>
          <a-form ref="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" :model="searchParams" :rules="rules">
            <a-row>
              <a-col :md="6" :sm="24">
                <a-form-item label="关键词" name="condition">
                  <a-input v-model:value="searchParams.condition" allow-clear placeholder="请输入条码、名称等查询" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="仓库" name="scId">
                  <a-select v-model:value="searchParams.scId" allow-clear placeholder="请选择仓库"
                    :options="warehouseOptions" :field-names="{
                      label: 'name',
                      value: 'id',
                    }" :filter-option="false">
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-space>
                  <a-button type="primary" @click="$refs.selector.search()">
                    <template #icon>
                      <SearchOutlined />
                    </template>
                    查询
                  </a-button>
                  <a-button @click="resetSearch">
                    <template #icon>
                      <ReloadOutlined />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </j-border>
      </template>
    </dialog-table>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { bomProductApi } from '/@/api/base-data/product/bom-product';
import { selector } from '/@/api/base-data/store-center';
import { searchProducts } from '/@/api/sc/stock/transfer-sc';
export default defineComponent({
  name: 'ProductionSelector',
  components: { SearchOutlined, ReloadOutlined },
  props: {
    modelValue: {
      type: String,
      default: ''
    },
    materialCode: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'product-selected', 'update:value'],
  data() {
    return {
      warehouseOptions: [],
      searchParams: {
        code: '',
        name: '',
        id: '',
        warehouse: undefined,
        // condition: '',
        // scId: undefined,
        available: this.$enums.AVAILABLE.ENABLE.code,
      },
      title: '选择商品',
      tableColumns: [
        { field: 'code', title: '商品编码', width: 120 },
        { field: 'name', title: '名称', minWidth: 160 },
        { field: 'shortName', title: '间称', minWidth: 160 },
        { field: 'skuCode', title: 'SKU编号', minWidth: 160 },
        { field: 'categoryName', title: '分类', minWidth: 160 },
        { field: 'brandName', title: '品牌', minWidth: 160 },
        {
          field: 'productType',
          title: '商品类型',
          minWidth: 160,
          formatter: ({ cellValue }) => {
            return this.$enums.PRODUCT_TYPE.getDesc(cellValue);
          },
        },
      ]
    };
  },
  computed: {
    _requestParams() {
      return { available: true, ...this.searchParams };
    },
    _columnOption() {
      return {
        label: 'code',
        value: 'code',
      }
    },
    _previousValue() {
      if (this.materialCode) { // 确保 this.$refs.selector 已经被初始化
        console.log("==================qweqweq==========>显示数据", this.materialCode);
        // 确保 this.$refs.selector 存在并且有 label 属性
        this.$nextTick(() => {
          if (typeof this.$refs.selector.label !== 'undefined') {
            this.$refs.selector.label = this.materialCode;
          }
        });
        return this.materialCode;
      }
      return ''; // 或者返回一个默认值
    },
  },
  created() {
    this.getWarehouseOptions();
  },
  methods: {
    getWarehouseOptions() {
      selector({
        available: true,
        pageIndex: 1,
        pageSize: 20,
      }).then(res => {
        this.warehouseOptions = res.datas;
        //console.log('Warehouse options:', this.warehouseOptions);
      });
    },
    async getList(params) {
      console.log('Fetching product list with params:', params);
      const nameRes = await bomProductApi.query({
        available: true,
        ...params,
        code: '',
        name: params.code,
      });
      const codeRes = await bomProductApi.query({
        available: true,
        ...params,
        code: params.code,
        name: '',
      });
      // 使用 Set 对象的特性进行去重
      const uniqueSet = new Set([...nameRes.datas, ...codeRes.datas].map(item => JSON.stringify(item)));
      const result = {
        datas: Array.from(uniqueSet).map(item => JSON.parse(item)),
        total: nameRes.total + codeRes.total,
      };

      // const result = await searchProducts(params.scId, params.condition);

      //console.log('Merged and deduplicated result:', result);
      return result;
    },
    resetSearch() {
      this.searchParams = {
        code: '',
        name: '',
        id: '',
        warehouse: undefined,
        // condition: '',
        // scId: undefined,
        available: this.$enums.AVAILABLE.ENABLE.code,
      };
      this.handleSearch();
    },
    handleRowClick(row) {
      // console.log('Row clicked, 898088080====================================data:', row);
      if (!row) {
        console.warn('Row data is empty');
        return;
      }

      const selectedProduct = {
        code: row.code,
        name: row.name,
        id: row.id,
        unit: row.unit
      };

      // console.log("====================================jihiubhutgycv==================>", selectedProduct)
      // 更新v-model值
      this.$emit('update:value', selectedProduct.code);

      // 触发选择事件
      this.$emit('product-selected', selectedProduct);

      console.log('Emitting product-selected event with:', selectedProduct);

      // 使用nextTick确保事件发送后再关闭对话框
      this.$nextTick(() => {
        if (this.$refs.selector && typeof this.$refs.selector.close === 'function') {
          this.$refs.selector.close();
        }
      });
    },
    openSelector() {
      if (this.$refs.selector) {
        this.$refs.selector.show();
      }
    }
  },
});
</script>

<style lang="less" scoped>
.operator {
  margin-top: 16px;
}

;
</style>
